package com.link.base.core.util;

import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.redisclient.LinkRedisClient;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SerialUtil {

    public static final String DAY = "yyyyMMdd";

    public static void main(String[] args) {
        String currentSerial = getTodayNextCurrentSerial();
        System.out.println(currentSerial);
    }

    public static String getContractTodayNextCurrentSerial(String contractType) {
        String prefix = "";
        if ("SentinelCon".equals(contractType)) {
            prefix = "DD";
        }
        if ("FrameCon".equals(contractType)) {
            prefix = "KJ";
        }
        if ("PriceCon".equals(contractType)) {
            prefix = "JG";
        }
        if ("ModelCon".equals(contractType)) {
            prefix = "MJ";
        }
        return prefix + getCurrentDay() + getTodayNextCurrentSerial();
    }


    public static String getTodayNextCurrentSerial() {
        String currentSerial = getTodayContractCurrentSerial();
        Integer currentIntVal = Integer.valueOf(currentSerial);
        if (currentIntVal < 10) {
            return "000" + currentSerial;
        } else if (currentIntVal < 100) {
            return "00" + currentSerial;
        } else if (currentIntVal < 1000) {
            return "0" + currentSerial;
        } else if (currentIntVal < 10000) {
            return currentSerial;
        } else {
            throw new RuntimeException("合同流水号超出4位有效数字!");
        }

    }

    public static String getTodayContractCurrentSerial() {
        LinkRedisClient jedis = null;
        String dateStr = getCurrentDay();
        String contractRedisKey = "CONTRACT_KEY_" + dateStr;
        try {
            jedis = RedisUtil.getJedis();
            String currentSerial = jedis.get(contractRedisKey);
            if (StringUtils.isNull(currentSerial)) {
                jedis.set(contractRedisKey, "1");
                currentSerial = "1";
            } else {
                String nextSerial = String.valueOf(Integer.valueOf(currentSerial) + 1);
                jedis.set(contractRedisKey, nextSerial);
            }
            return currentSerial;
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    public static String getCurrentDay() {
        Date date = new Date();//获取当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat(DAY);//定义日期格式
        String dateStr = dateFormat.format(date);//将时间格式化为字符串
        return dateStr;
    }
}
